from PySide6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QPushButton,
                               QLabel, QFrame, QComboBox, QTableWidget,
                               QTableWidgetItem, QTabWidget)
from PySide6.QtCore import Qt, QDate
from PySide6.QtCharts import QChart, QChartView, QBarSeries, QBarSet, QBarCategoryAxis
from PySide6.QtGui import QPainter
from utils.db import db
from datetime import datetime, timedelta
import calendar


class ReportPage(QWidget):
    def __init__(self):
        super().__init__()
        self.setup_ui()
        self.load_data()

    def setup_ui(self):
        layout = QVBoxLayout(self)
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(20)

        # 顶部统计卡片
        self.setup_stat_cards()

        # 选项栏
        option_bar = QFrame()
        option_bar.setObjectName("optionBar")
        option_layout = QHBoxLayout(option_bar)

        # 时间范围选择
        self.period_combo = QComboBox()
        self.period_combo.addItems(["今日", "本周", "本月", "本年"])
        self.period_combo.currentIndexChanged.connect(self.load_data)

        option_layout.addWidget(QLabel("统计周期："))
        option_layout.addWidget(self.period_combo)
        option_layout.addStretch()

        # 刷新按钮
        refresh_btn = QPushButton("刷新数据")
        refresh_btn.setObjectName("primaryButton")
        refresh_btn.clicked.connect(self.load_data)
        option_layout.addWidget(refresh_btn)

        # 标签页
        tab_widget = QTabWidget()
        tab_widget.setObjectName("reportTabs")

        # 收入统计
        income_tab = QWidget()
        income_layout = QVBoxLayout(income_tab)
        self.income_chart_view = QChartView()
        self.income_chart_view.setRenderHint(QPainter.Antialiasing)
        income_layout.addWidget(self.income_chart_view)

        # 服务统计
        service_tab = QWidget()
        service_layout = QVBoxLayout(service_tab)
        self.service_table = QTableWidget()
        self.service_table.setColumnCount(4)
        self.service_table.setHorizontalHeaderLabels([
            "服务项目", "服务次数", "总收入", "平均客单价"
        ])
        service_layout.addWidget(self.service_table)

        # 员工业绩
        staff_tab = QWidget()
        staff_layout = QVBoxLayout(staff_tab)
        self.staff_table = QTableWidget()
        self.staff_table.setColumnCount(4)
        self.staff_table.setHorizontalHeaderLabels([
            "员工", "服务次数", "创造收入", "平均业绩"
        ])
        staff_layout.addWidget(self.staff_table)

        # 添加标签页
        tab_widget.addTab(income_tab, "收入统计")
        tab_widget.addTab(service_tab, "服务统计")
        tab_widget.addTab(staff_tab, "员工业绩")

        # 添加到主布局
        layout.addWidget(self.stat_cards)
        layout.addWidget(option_bar)
        layout.addWidget(tab_widget)

        self.apply_styles()

    def setup_stat_cards(self):
        self.stat_cards = QFrame()
        self.stat_cards.setObjectName("statCards")
        cards_layout = QHBoxLayout(self.stat_cards)

        # 创建统计卡片
        self.total_income_label = self.create_stat_card("总收入", "¥0.00", "收入统计")
        self.total_orders_label = self.create_stat_card("订单数", "0", "服务统计")
        self.total_members_label = self.create_stat_card("会员数", "0", "会员总数")
        self.avg_price_label = self.create_stat_card("平均客单价", "¥0.00", "客单价")

        cards_layout.addWidget(self.total_income_label)
        cards_layout.addWidget(self.total_orders_label)
        cards_layout.addWidget(self.total_members_label)
        cards_layout.addWidget(self.avg_price_label)

    def create_stat_card(self, title, value, subtitle):
        card = QFrame()
        card.setObjectName("statCard")
        layout = QVBoxLayout(card)

        title_label = QLabel(title)
        title_label.setObjectName("cardTitle")

        value_label = QLabel(value)
        value_label.setObjectName("cardValue")

        subtitle_label = QLabel(subtitle)
        subtitle_label.setObjectName("cardSubtitle")

        layout.addWidget(title_label)
        layout.addWidget(value_label)
        layout.addWidget(subtitle_label)

        return card

    def get_date_range(self):
        period = self.period_combo.currentText()
        today = datetime.now()

        if period == "今日":
            start_date = today.replace(hour=0, minute=0, second=0, microsecond=0)
            end_date = today.replace(hour=23, minute=59, second=59, microsecond=999999)
        elif period == "本周":
            start_date = today - timedelta(days=today.weekday())
            end_date = start_date + timedelta(days=6)
        elif period == "本月":
            start_date = today.replace(day=1)
            end_date = today.replace(day=calendar.monthrange(today.year, today.month)[1])
        else:  # 本年
            start_date = today.replace(month=1, day=1)
            end_date = today.replace(month=12, day=31)

        return start_date, end_date

    def load_data(self):
        start_date, end_date = self.get_date_range()

        # 加载基础统计数据
        self.load_basic_stats(start_date, end_date)

        # 加载收入图表
        self.load_income_chart(start_date, end_date)

        # 加载服务统计
        self.load_service_stats(start_date, end_date)

        # 加载员工业绩
        self.load_staff_stats(start_date, end_date)

    def load_basic_stats(self, start_date, end_date):
        # 总收入和订单数
        sql = """
        SELECT 
            COUNT(*) as order_count,
            SUM(amount) as total_income,
            AVG(amount) as avg_price
        FROM transactions
        WHERE created_at BETWEEN ? AND ?
        """
        result = db.fetch_one(sql, (start_date, end_date))

        # 会员数
        sql = "SELECT COUNT(*) as member_count FROM members"
        member_result = db.fetch_one(sql)

        # 更新统计卡片
        self.total_income_label.findChild(QLabel, "cardValue").setText(
            f"¥{result['total_income'] or 0:.2f}")
        self.total_orders_label.findChild(QLabel, "cardValue").setText(
            str(result['order_count']))
        self.total_members_label.findChild(QLabel, "cardValue").setText(
            str(member_result['member_count']))
        self.avg_price_label.findChild(QLabel, "cardValue").setText(
            f"¥{result['avg_price'] or 0:.2f}")

    def load_income_chart(self, start_date, end_date):
        # 创建图表
        chart = QChart()
        chart.setAnimationOptions(QChart.SeriesAnimations)
        chart.setTitle("收入统计")

        # 创建数据系列
        series = QBarSeries()
        income_set = QBarSet("收入")

        # 获取数据
        sql = """
        SELECT DATE(created_at) as date,
               SUM(amount) as daily_income
        FROM transactions
        WHERE created_at BETWEEN ? AND ?
        GROUP BY DATE(created_at)
        ORDER BY date
        """
        results = db.fetch_all(sql, (start_date, end_date))

        # 添加数据
        dates = []
        for row in results:
            income_set.append(float(row['daily_income']))
            dates.append(row['date'])

        series.append(income_set)
        chart.addSeries(series)

        # 设置坐标轴
        axis_x = QBarCategoryAxis()
        axis_x.append(dates)
        chart.setAxisX(axis_x)

        # 更新图表视图
        self.income_chart_view.setChart(chart)

    def load_service_stats(self, start_date, end_date):
        sql = """
        SELECT 
            s.name,
            COUNT(*) as service_count,
            SUM(t.amount) as total_income,
            AVG(t.amount) as avg_price
        FROM transactions t
        JOIN services s ON t.service_id = s.id
        WHERE t.created_at BETWEEN ? AND ?
        GROUP BY s.id
        ORDER BY total_income DESC
        """
        results = db.fetch_all(sql, (start_date, end_date))

        self.service_table.setRowCount(len(results))
        for row, data in enumerate(results):
            self.service_table.setItem(row, 0, QTableWidgetItem(data['name']))
            self.service_table.setItem(row, 1, QTableWidgetItem(str(data['service_count'])))
            self.service_table.setItem(row, 2, QTableWidgetItem(f"¥{data['total_income']:.2f}"))
            self.service_table.setItem(row, 3, QTableWidgetItem(f"¥{data['avg_price']:.2f}"))

    def load_staff_stats(self, start_date, end_date):
        sql = """
        SELECT 
            u.display_name,
            COUNT(*) as service_count,
            SUM(t.amount) as total_income,
            AVG(t.amount) as avg_income
        FROM transactions t
        JOIN users u ON t.staff_id = u.id
        WHERE t.created_at BETWEEN ? AND ?
        GROUP BY u.id
        ORDER BY total_income DESC
        """
        results = db.fetch_all(sql, (start_date, end_date))

        self.staff_table.setRowCount(len(results))
        for row, data in enumerate(results):
            self.staff_table.setItem(row, 0, QTableWidgetItem(data['display_name']))
            self.staff_table.setItem(row, 1, QTableWidgetItem(str(data['service_count'])))
            self.staff_table.setItem(row, 2, QTableWidgetItem(f"¥{data['total_income']:.2f}"))
            self.staff_table.setItem(row, 3, QTableWidgetItem(f"¥{data['avg_income']:.2f}"))

    def apply_styles(self):
        self.setStyleSheet("""
            QWidget {
                background-color: #f5f6fa;
            }
            #statCards {
                background: transparent;
            }
            #statCard {
                background-color: white;
                border-radius: 10px;
                padding: 15px;
                margin: 5px;
            }
            #cardTitle {
                color: #2f3542;
                font-size: 14px;
            }
            #cardValue {
                color: #5352ed;
                font-size: 24px;
                font-weight: bold;
                margin: 10px 0;
            }
            #cardSubtitle {
                color: #747d8c;
                font-size: 12px;
            }
            #optionBar {
                background-color: white;
                border-radius: 10px;
                padding: 10px;
            }
            #reportTabs {
                background-color: white;
                border-radius: 10px;
            }
            QTabWidget::pane {
                border: none;
                background-color: white;
                border-radius: 10px;
            }
            QTabBar::tab {
                background-color: #f1f2f6;
                color: #2f3542;
                padding: 8px 15px;
                margin-right: 2px;
                border-top-left-radius: 5px;
                border-top-right-radius: 5px;
            }
            QTabBar::tab:selected {
                background-color: #5352ed;
                color: white;
            }
            QTableWidget {
                border: none;
                gridline-color: #f1f2f6;
            }
            QTableWidget::item {
                padding: 8px;
            }
            QHeaderView::section {
                background-color: #f8f9fa;
                padding: 8px;
                border: none;
                border-bottom: 2px solid #dcdde1;
            }
            #primaryButton {
                background-color: #5352ed;
                color: white;
                border: none;
                padding: 8px 15px;
                border-radius: 4px;
            }
            #primaryButton:hover {
                background-color: #3742fa;
            }
        """)
